package com.study.sbsummary.utils;

import com.google.common.base.CharMatcher;
import com.google.common.base.Strings;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Component
@Data
public class MD5CodingUtil {
    private static String KSS_AK;  //AccessKey
    private static String KSS_SK;
    public static final String APP_ID = "truelyimg";
    private static final String SECRET_KEY = "D1Oft6kLOBQGiuqMtYepP644EDWSdElP";
    private static final String URI = "/image.php";

    public static final String IMG_URL = "https://ibz2.go2yd.com/image.php";
    public static final String IMG_TEST_URL = "https://ib-test.go2yd.com/image.php";
    private static final String TEST_IMAGE_RE = "^(http(s)?://)?i1-test\\.go2yd\\.com/image(?:\\.php\\?url=|/)([A-Za-z0-9_]{8,60})$";
    private static final String PROD_IMAGE_RE = "^(http(s)?://)?i\\w*?\\.go2yd\\.com/image(?:\\.php\\?url=|/)([A-Za-z0-9_]{8,60})$";

    private static final String TEST_ENCRY_IMAGE_RE = "^(http(s)?://)?ib-test\\.go2yd\\.com/image(?:\\.php\\?url=|/)*$";
    private static final String PROD_ENCRY_IMAGE_RE = "^(http(s)?://)?ibz2\\.go2yd\\.com/image(?:\\.php\\?url=|/)*$";

    private static final String SPLIT = "-";

    @Value("${kss.ak}")
    public void setKssAK(String env) {
        MD5CodingUtil.KSS_AK = env;
    }

    @Value("${kss.sk}")
    public void setKssSK(String env) {
        MD5CodingUtil.KSS_SK = env;
    }

    public static String getPicUrlCode(String picUrl, Long ts) {
        String bf = APP_ID +
                SPLIT + SECRET_KEY +
                SPLIT + URI +
                SPLIT + ts +
                SPLIT + picUrl;

        String token = DigestUtils.md5DigestAsHex(bf.getBytes());
        return token;
    }

    public static String convertImgId2AuthUrl(String imageId, String env) {
        String imgUrl = "";
        if (Strings.isNullOrEmpty(imageId)) {
            return imgUrl;
        }
        if (imageId.startsWith("http")) {
            imgUrl = dealUrlStr(imageId);
        }
        // 如果imageUrl是空，就是根据id拼接
        return imgUrl.isEmpty() ? concatAuthUrl(imageId, env) : imgUrl;
    }

    public static String removeUrlToken(String imageUrl) {
        String originUrl = imageUrl;
        try {
            if (Strings.isNullOrEmpty(imageUrl)){
                return imageUrl;
            }
            String envString = "";
            int start = StringUtils.ordinalIndexOf(imageUrl, "=", 1)+1;
            int end = StringUtils.ordinalIndexOf(imageUrl, "&", 1);
            if (imageUrl.startsWith("https://ib-test") || imageUrl.contains("http://ib-test")) {
                envString = "test";
                imageUrl = imageUrl.substring(start, end);
            } else if (imageUrl.startsWith("https://ibz2") || imageUrl.contains("http://ibz2")) {
                envString = "prod";
                imageUrl = imageUrl.substring(start, end);
            }

            if (envString.equals("test")) {
                imageUrl = "https://i1-test.go2yd.com/image.php?url="+imageUrl;
            } else if (envString.equals("prod")){
                imageUrl = "https://i1.go2yd.com/image.php?url="+imageUrl;
            }
            return imageUrl;
        }catch (Exception e){
            log.error("解析防盗链url到普通链接失败",e);
            return originUrl;
        }
    }

    private static String concatAuthUrl(String imageId, String env) {
        long milli = LocalDateTime.now().plusMinutes(15).toEpochSecond(ZoneOffset.of("+8"));
        String authKey = getPicUrlCode(imageId, milli);
        if (env.equals("test")) {
            return String.format("%s?url=%s&timestamp=%s&auth_id=%s&auth_key=%s", IMG_TEST_URL, imageId, milli, APP_ID, authKey);
        } else {
            return String.format("%s?url=%s&timestamp=%s&auth_id=%s&auth_key=%s", IMG_URL, imageId, milli, APP_ID, authKey);
        }
    }

    private static String dealUrlStr(String imageId) {
        String patternStr;
        if (imageId.startsWith("https://i1-test") || imageId.contains("http://i1-test")) {
            patternStr = TEST_IMAGE_RE;
        } else if (imageId.startsWith("https://i") || imageId.contains("http://i")) {
            patternStr = PROD_IMAGE_RE;
        } else {
            return imageId;
        }
        // 如果是链接形式，就去尝试抽取imageid。
        if (!Strings.isNullOrEmpty(patternStr)) {
            try {
                Pattern pattern = Pattern.compile(patternStr);
                Matcher matcher = pattern.matcher(imageId);
                boolean result = matcher.find();
                if (result) {
                    int i = matcher.groupCount();
                    imageId = matcher.group(i);
                }
            } catch (RuntimeException e) {
                log.error("从链接中抽取id失败: {}", e.getMessage());
            }
        }
        if (patternStr.equals(TEST_IMAGE_RE)) {
            return concatAuthUrl(imageId, "test");
        } else {
            return concatAuthUrl(imageId, "prod");
        }
    }


    public static String getVideoUrlCode(String methods, String bucket,
                                         String objectKey) {
        long expireTime = LocalDateTime.now().plusMinutes(15).toEpochSecond(ZoneOffset.of("+8"));
        String sign = methods + "\n" + "" + "\n" + "" + "\n" + expireTime + "\n" + bucket + objectKey;
        String hmacSHA1 = "";
        try {
            hmacSHA1 = HMACSHA1.getSignature(sign, KSS_SK);
        } catch (Exception e) {
            log.error("get crypto url failed：{}", e.getMessage());
        }
        return String.format("http://ks3-cn-beijing.ksyun.com" +
                        "%s?KSSAccessKeyId=%s&Expires=%s&Signature=%s",
                bucket + objectKey, KSS_AK, expireTime, hmacSHA1);
    }

    public static String convertVideoUrl(String videoUrl) {
        if (Strings.isNullOrEmpty(videoUrl)) {
            return "";
        }
        // 提取第一段url
        int i = CharMatcher.anyOf("/").indexIn(videoUrl, 10);
        String uri = videoUrl.substring(i);   // /video-yidian/localside-ugc/live_iOS_1646740167253.mp4
        int objectKeyIndex = CharMatcher.anyOf("/").indexIn(uri, 2);
        String objectKey = uri.substring(objectKeyIndex);
        String expireUrl = getVideoUrlCode("GET", uri.substring(0, objectKeyIndex), objectKey);
        return expireUrl;
    }
}
